package licode.unisop.authcenter.application.executor;

import licode.unisop.client.api.auth.SopUserAuthQuery;
import licode.unisop.client.info.SopTokenInfo;
import licode.unisop.client.vo.SopUserBrief;
import licode.unisop.platform.client.api.SiPlatformAuthService;
import licode.unisop.platform.client.api.SiPlatformQueryService;
import licode.unisop.platform.client.vo.PlatAuthVO;
import licode.unisop.provider.info.SiHoldInfo;
import licode.unisop.provider.info.SiPlatIdFind;
import licode.unisop.provider.vo.SiAssetBO;
import licode.unisop.provider.vo.SiAssetHold;
import licode.unisop.types.AuthConst;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定义统一认证平台中心认证相关接口
 *
 * @author licode
 */
@Service
public class CenterAuthExecutor {
    @Resource
    private SopUserAuthQuery queryAuth;

    @Resource
    private SiPlatformAuthService siPlatformAuthService;

    @Resource
    private SiPlatformQueryService siPlatformQueryService;

    public Map<String, Object> getUserAssets(SopTokenInfo tokenInfo) {
        SiAssetHold assetHold;
        Map<String, Object> result = new HashMap<>();
        SopUserBrief user = queryAuth.getUserInfo(tokenInfo);
        PlatAuthVO platAuth = siPlatformAuthService.fromId(SiPlatIdFind.builder()
                .platformId(tokenInfo.getPlatformId()).build());
        SiHoldInfo holdInfo = SiHoldInfo.builder()
                .holdId(user.getUserId())
                .tenantId("")
                .platformId(platAuth.getPlatformId())
                .build();

        assetHold = siPlatformQueryService.getUserAssets(holdInfo);
        if (null != assetHold.getCodes()) {
            Map<String, String> roleCodes = assetHold.getCodes().get("ROLE");
            // 超级管理员，重新获取所有资源
            if (null != roleCodes && roleCodes.containsKey(AuthConst.SYSTEM_ADMIN)) {
                holdInfo.setHoldId("");
                assetHold = siPlatformQueryService.getUserAssets(holdInfo);
            }
        }

        if (null != assetHold.getTrees()) {
            List<SiAssetBO> menus = assetHold.getTrees().get("MENU");
            result.put("menus", null == menus ? new ArrayList<>(): menus);
        }

        if (null != assetHold.getCodes()) {
            Map<String, String> roleCodes = assetHold.getCodes().get("ROLE");
            result.put("roleCodes", null == roleCodes ? new ArrayList<>(): new ArrayList<>(roleCodes.keySet()));
            Map<String, String> permitCodes = assetHold.getCodes().get("PERMIT");
            result.put("permitCodes", null == permitCodes ? new ArrayList<>(): new ArrayList<>(permitCodes.keySet()));
        }

        return result;
    }
}
